const express = require('express');
const auth = require('../../middleware/auth');

const router = express.Router();

// 模拟访客数据
let visitorsData = [
  {
    id: '1',
    name: '张三',
    phone: '13800138000',
    idCard: '110101199001011234',
    company: '科技有限公司',
    visitPurpose: '商务洽谈',
    visitee: '李经理',
    visitTime: ['2024-01-15 09:00', '2024-01-15 17:00'],
    status: 'approved',
    qrCode: 'VIS001',
    vehiclePlate: '京A12345',
    createdAt: '2024-01-14 10:00:00'
  },
  {
    id: '2',
    name: '李四',
    phone: '13800138001',
    company: '设计工作室',
    visitPurpose: '技术交流',
    visitee: '王总监',
    visitTime: ['2024-01-16 14:00', '2024-01-16 18:00'],
    status: 'pending',
    qrCode: 'VIS002',
    createdAt: '2024-01-15 09:30:00'
  },
  {
    id: '3',
    name: '王五',
    phone: '13700137000',
    company: '咨询公司',
    visitPurpose: '参观考察',
    visitee: '陈主任',
    visitTime: ['2024-01-17 10:00', '2024-01-17 12:00'],
    status: 'rejected',
    qrCode: 'VIS003',
    createdAt: '2024-01-15 11:00:00'
  }
];

// 生成二维码
const generateQRCode = () => {
  return 'VIS' + String(Date.now()).slice(-6);
};

// 获取访客列表
router.get('/', auth, async (req, res) => {
  try {
    const { status, date, visitee } = req.query;
    let filteredVisitors = visitorsData;
    
    // 根据查询参数过滤
    if (status) {
      filteredVisitors = filteredVisitors.filter(visitor => visitor.status === status);
    }
    if (visitee) {
      filteredVisitors = filteredVisitors.filter(visitor => 
        visitor.visitee.toLowerCase().includes(visitee.toLowerCase())
      );
    }
    if (date) {
      filteredVisitors = filteredVisitors.filter(visitor => 
        visitor.visitTime[0].startsWith(date)
      );
    }
    
    res.json({
      success: true,
      data: filteredVisitors,
      total: filteredVisitors.length
    });
  } catch (error) {
    console.error('Get visitors error:', error);
    res.status(500).json({ error: '获取访客列表失败' });
  }
});

// 获取单个访客信息
router.get('/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const visitor = visitorsData.find(v => v.id === id);
    
    if (!visitor) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    res.json({
      success: true,
      data: visitor
    });
  } catch (error) {
    console.error('Get visitor error:', error);
    res.status(500).json({ error: '获取访客信息失败' });
  }
});

// 创建访客记录
router.post('/', auth, async (req, res) => {
  try {
    const { name, phone, idCard, company, visitPurpose, visitee, visitTime, vehiclePlate } = req.body;
    
    // 验证必填字段
    if (!name || !phone || !company || !visitPurpose || !visitee || !visitTime) {
      return res.status(400).json({ error: '请填写所有必填字段' });
    }
    
    // 验证访问时间
    if (!Array.isArray(visitTime) || visitTime.length !== 2) {
      return res.status(400).json({ error: '访问时间格式错误' });
    }
    
    const newVisitor = {
      id: Date.now().toString(),
      name,
      phone,
      idCard,
      company,
      visitPurpose,
      visitee,
      visitTime,
      vehiclePlate,
      status: 'pending',
      qrCode: generateQRCode(),
      createdAt: new Date().toLocaleString('zh-CN')
    };
    
    visitorsData.push(newVisitor);
    
    res.status(201).json({
      success: true,
      data: newVisitor,
      message: '访客记录创建成功'
    });
  } catch (error) {
    console.error('Create visitor error:', error);
    res.status(500).json({ error: '创建访客记录失败' });
  }
});

// 更新访客记录
router.put('/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { name, phone, idCard, company, visitPurpose, visitee, visitTime, vehiclePlate } = req.body;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    visitorsData[visitorIndex] = {
      ...visitorsData[visitorIndex],
      name: name || visitorsData[visitorIndex].name,
      phone: phone || visitorsData[visitorIndex].phone,
      idCard: idCard || visitorsData[visitorIndex].idCard,
      company: company || visitorsData[visitorIndex].company,
      visitPurpose: visitPurpose || visitorsData[visitorIndex].visitPurpose,
      visitee: visitee || visitorsData[visitorIndex].visitee,
      visitTime: visitTime || visitorsData[visitorIndex].visitTime,
      vehiclePlate: vehiclePlate || visitorsData[visitorIndex].vehiclePlate,
      updatedAt: new Date().toLocaleString('zh-CN')
    };
    
    res.json({
      success: true,
      data: visitorsData[visitorIndex],
      message: '访客记录更新成功'
    });
  } catch (error) {
    console.error('Update visitor error:', error);
    res.status(500).json({ error: '更新访客记录失败' });
  }
});

// 删除访客记录
router.delete('/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    const deletedVisitor = visitorsData.splice(visitorIndex, 1)[0];
    
    res.json({
      success: true,
      data: deletedVisitor,
      message: '访客记录删除成功'
    });
  } catch (error) {
    console.error('Delete visitor error:', error);
    res.status(500).json({ error: '删除访客记录失败' });
  }
});

// 审核通过
router.post('/:id/approve', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    visitorsData[visitorIndex].status = 'approved';
    visitorsData[visitorIndex].approvedAt = new Date().toLocaleString('zh-CN');
    visitorsData[visitorIndex].approvedBy = req.user.username;
    
    console.log(`Visitor ${id} approved by ${req.user.username}`);
    
    res.json({
      success: true,
      data: visitorsData[visitorIndex],
      message: '访客审核通过'
    });
  } catch (error) {
    console.error('Approve visitor error:', error);
    res.status(500).json({ error: '审核失败' });
  }
});

// 审核拒绝
router.post('/:id/reject', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { reason } = req.body;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    visitorsData[visitorIndex].status = 'rejected';
    visitorsData[visitorIndex].rejectedAt = new Date().toLocaleString('zh-CN');
    visitorsData[visitorIndex].rejectedBy = req.user.username;
    visitorsData[visitorIndex].rejectReason = reason;
    
    console.log(`Visitor ${id} rejected by ${req.user.username}`);
    
    res.json({
      success: true,
      data: visitorsData[visitorIndex],
      message: '访客审核拒绝'
    });
  } catch (error) {
    console.error('Reject visitor error:', error);
    res.status(500).json({ error: '审核失败' });
  }
});

// 访客签到
router.post('/:id/checkin', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    if (visitorsData[visitorIndex].status !== 'approved') {
      return res.status(400).json({ error: '访客未通过审核，无法签到' });
    }
    
    visitorsData[visitorIndex].checkedInAt = new Date().toLocaleString('zh-CN');
    visitorsData[visitorIndex].status = 'checked_in';
    
    res.json({
      success: true,
      data: visitorsData[visitorIndex],
      message: '签到成功'
    });
  } catch (error) {
    console.error('Check in visitor error:', error);
    res.status(500).json({ error: '签到失败' });
  }
});

// 访客签出
router.post('/:id/checkout', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const visitorIndex = visitorsData.findIndex(v => v.id === id);
    if (visitorIndex === -1) {
      return res.status(404).json({ error: '访客记录不存在' });
    }
    
    visitorsData[visitorIndex].checkedOutAt = new Date().toLocaleString('zh-CN');
    visitorsData[visitorIndex].status = 'completed';
    
    res.json({
      success: true,
      data: visitorsData[visitorIndex],
      message: '签出成功'
    });
  } catch (error) {
    console.error('Check out visitor error:', error);
    res.status(500).json({ error: '签出失败' });
  }
});

module.exports = router;